package com.ad2campaign.engine.rest;

import java.util.List;
import java.util.Set;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.ad2campaign.engine.db.model.Node;

public class NodeMonitor extends TimerTask
{
	private List<Node> runningNodes;
 	private Set<Node> blacklistedNodes;
 	private Action pingAction;
 	private ActionExecutor actionExecutor;
 	private static final Logger LOGGER = Logger.getLogger(NodeMonitor.class);
 	
 	
	
	public NodeMonitor(Set<Node> blacklistedNodes,List<Node> runningNodes, ActionExecutor actionExecutor,Action pingAction)
	{
		this.blacklistedNodes=blacklistedNodes;
		this.actionExecutor =  actionExecutor;
		this.runningNodes = runningNodes;
		this.pingAction=pingAction;
	}

 	

	@Override
	public void run() 
	{
	 	if (runningNodes!=null)
			{
 				for (Node node :  runningNodes)
				{
 					if (LOGGER.isDebugEnabled())
 					{
 						LOGGER.debug("Checking alive status of node ["+node+"]");
 					}

 					boolean isAlive=actionExecutor.isAlive(node,pingAction);
					LOGGER.debug("Checking alive status of node ["+node+"] is ["+isAlive+"]");
					if (!isAlive )
					{	
	 					if (LOGGER.isDebugEnabled())
 						{
 							LOGGER.debug("Node ["+node+"] is added to blacklist");
 	
 						}
 						blacklistedNodes.add(node);
					}
					else
					{
						if (blacklistedNodes.contains(node))
						{
							blacklistedNodes.remove(node);
						}
					}
 				}
			}
 	}
	

	

	
	
}
